#include "comm.hpp"

void getMessage(int fd)
{ 
    //3.通信代码
    char buff[SIZE];
    while(true)
    {
        memset(buff,0,sizeof(buff));
        ssize_t s = read(fd,buff,sizeof(buff) - 1);
        if(s > 0)
        {
            cout << "client say->" << buff << endl;
        }
        else if(s == 0)
        {
            cerr << "read end of file ,client quit ,server quit too!" << endl;
            break;
        }
        else
        {
            perror("read");
            exit(1);
        }
    }
}

int main()
{
    //1.创建管道文件
    if(mkfifo(ipcPath.c_str(),MODE) < 0)
    {
        perror("mkfifo");
        exit(1);
    }

    //2.文件操作
    int fd = open(ipcPath.c_str(),O_RDONLY);
    if(fd < 0) 
    {
        perror("open");
        exit(1);
    }

    int nums = 3;
    for(int i = 0;i < nums;++i)
    {
        pid_t id = fork();
        if(id == 0)
        {
            getMessage(fd);
            exit(1);
        }
    } 

    for(int i = 0;i < nums;++i)
    {
        pid_t ret = waitpid(-1,nullptr,0);
    }

    close(fd);
    unlink(ipcPath.c_str());//删除管道文件
    return 0;
}